import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null){
            return null;
        }
        TreeNode head = pRootOfTree;
        while(head.left != null){
            head = head.left;
        }
        fun(pRootOfTree, head);
        return head;
    }

    public void fun(TreeNode root, TreeNode head){
        Stack<TreeNode> s = new Stack<>();
        ArrayList<TreeNode> list = new ArrayList<>();
        if(root == null){
            return;
        }
        s.push(root);
        while(!s.isEmpty()){
            TreeNode cur = s.peek();
            if(cur.left != null){
                s.push(cur.left);
                cur.left = null;
            } else {
                s.pop();
                list.add(cur);
                if(cur.right != null){
                    s.push(cur.right);
                }
            }
        }
        TreeNode cur = head;
        cur.left = null;
        for(int i = 1;i<list.size();i++){
            TreeNode right = list.get(i);
            cur.right = right;
            right.left = cur;
            cur = right;
        }
        
    }
}
